package dynamic

import (
	"meetroom/server/IOC"
	"meetroom/server/manage"
	"net/http"
	"path"
	"strings"

	"github.com/garyburd/redigo/redis"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

func dynamicView(db *gorm.DB, rC *redis.Conn) manage.Viewer {
	v := manage.QuickNewViewer("/:divPath/:urlPath", db, rC, manage.NewHandle(manage.GET, dynamicPageHandle))

	return v
}
func pathCheck(path string) string {
	if strings.HasPrefix(path, "/") {
		return "/dynamic" + path
	}
	return path
}

type TempData struct {
	RequireJs  []string
	RequireCss []string
	Start      string
	Title      string
}

type DynamicAction struct {
	DivPath IOC.Value `ioc:"from:path;to:string;name:divPath"`
	URIPath IOC.Value `ioc:"from:path;to:string;name:urlPath"`
}

func dynamicPageHandle(db *gorm.DB, rc *redis.Conn) gin.HandlerFunc {

	return func(c *gin.Context) {
		var divpath, UriPath string
		divpath = c.Param("divPath")
		UriPath = c.Param("urlPath")
		
		var data TempData

		data.RequireJs = append(data.RequireJs, configData.GlobalJS...)
		data.RequireCss = append(data.RequireCss, configData.GlobalCss...)

		targetApp, ok := configData.Apps[divpath]
		if !ok {
			panic("no config find about " + divpath + "/" + UriPath)
		}

		data.RequireJs = append(data.RequireJs, targetApp.AppJs...)
		data.RequireCss = append(data.RequireCss, targetApp.AppCss...)

		targetURI, ok := targetApp.URIs[UriPath]
		if !ok {
			panic("no config find about " + divpath + "/" + UriPath)
		}

		data.RequireCss = append(data.RequireCss, targetURI.RequireCss...)
		data.RequireJs = append(data.RequireJs, targetURI.RequireJs...)

		data.Start = targetURI.StartJS
		data.Title = targetURI.Title

		c.HTML(http.StatusOK, "page.html", data)
		c.Abort()
	}
}
func ToDynamicPath(filePath string)string{
	if strings.HasPrefix(filePath,"/"){
		return path.Join("/api/dynamic/file",filePath)
	}
	return filePath;
}